package ai.people.netmon.warning.assist;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * 锁定操作
 *
 * @author LiGuanNan
 * @date 2022/8/15 15:42
 */
@Slf4j
@Component
public class LockAction {
    @Autowired
    private RedissonClient redissonClient;

    public <R> R doLockTask(String lockKey, Integer timeout, Callable<R> task) {
        RLock lock = redissonClient.getLock(lockKey);
        try {
            if (Objects.nonNull(lockKey) && Objects.nonNull(timeout) && !lock.tryLock(timeout, TimeUnit.SECONDS)) {
                return null;
            }
            log.info("获取分布式锁成功, lockKey:{}", lockKey);
            return task.call();
        }catch (InterruptedException e){
            log.error("等待锁的线程被中止", e);
            return null;
        }catch (Exception e) {
            log.warn("任务执行报错", e);
            return null;
        }finally {
            if (Objects.nonNull(lockKey)) {
                if(lock.isHeldByCurrentThread()){
                    log.info("释放分布式锁成功, lockKey:{}", lockKey);
                    lock.unlock();
                }
            }
        }
    }
}
